package com.ysxsoft.wdg.net.interceptor;

import android.support.annotation.NonNull;

import com.socks.library.KLog;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 */
public class LoggerInterceptor implements Interceptor {
    private static final String TAG = "RequestLog";

    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        //发送
        long requestTime = System.currentTimeMillis();
        Request request = chain.request();
        //
        //接收
        Response response = chain.proceed(chain.request());
        ResponseBody responseBody = response.peekBody(1024 * 1024);
        long responseTime = System.currentTimeMillis();
        long delayTime = responseTime - requestTime;
        KLog.d(TAG, "requestUrl:" + request.url().toString()
                , "params:" + getParams(request)
                , "delayTime:" + delayTime
                , "content:");
        KLog.json(TAG, responseBody.string());
        return response;
    }

    //
    private String getParams(Request request) {
        String method = request.method();
        StringBuilder sb = new StringBuilder();
        if ("POST".equals(method)) {
            if (request.body() instanceof FormBody) {
                FormBody body = (FormBody) request.body();
                if (body != null) {
                    for (int i = 0; i < body.size(); i++) {
                        sb.append(body.encodedName(i)).append("=").append(body.encodedValue(i)).append("\n");
                    }
                }
                sb.delete(sb.length() - 1, sb.length());
            }
        }
        return sb.toString();
    }
}
